package com.acme.domain.email.impl;

import java.util.ArrayList;
import java.util.List;

import com.acme.domain.email.Email;
import com.acme.domain.email.Queue;

public class QueueImpl implements Queue {
	private boolean opened = true;

	List<Email> mails = new ArrayList<Email>();

	public synchronized void addEmail(Email email) {
		if(this.opened) {
			this.mails.add(email);
			notifyAll();
		}
	}
	
	public synchronized Email getEmail(){
		if(this.mails.size() < 1) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		// TODO: [VY] After thread wake up, there isn't 
//		any guarantee that queue will have more than 0 elements. 
//		You can obtaine the following IndexOutOfBoundsException. 
//		Please fix it. 
		else {
			return mails.remove(0);
		}
		return null;
	}

	public synchronized void close() {
		this.opened = false;
		notifyAll();
	}
	
	public List<Email> getEmails() {
		return this.mails;
	}

	@Override
	public Email getEmail(int id) {
		for(Email email: mails) {
			if(email.getId() == id) {
				return email;
			}
		}
		return null;
	}

	public synchronized boolean isOpened() {
		return this.opened;
	}
}
